package com.shebei.api.equipment_api_test.config;


import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.shebei.api.equipment_api_test.dao", sqlSessionFactoryRef = "uniubiSqlSessionFactory")
public class UniubiConfigure {

    @Bean(name = "uniubiDataSource")
    @ConfigurationProperties("spring.datasource.uniubi")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "uniubiSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("uniubiDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/*.xml"));
        return sessionFactoryBean.getObject();
    }

    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("uniubiSqlSessionFactory") SqlSessionFactory sqlSessionFactory)
            throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);  //使用上面配置的sqlsesionFactory
        return template;
    }
}
